# from __future__ import absolute_import, unicode_literals
import os
import shutil

from celery import shared_task
import time
import json
from tools.myredis import r
from tools.baiduapi import bdapi
from users.models import IdentityModel
from users.serial import IdentitySerializer
from webs.webstest import ssh
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from order.views import CheckOrder


# @shared_task
# def cheduler_task(name):
#     end = int(time.time()) - 600
#     olist = r.sorted_times(key, 0, end)
#     for i in olist:
#         res = alipay.query_pay(i.decode())
#         requests
#         content = res.text
#         # 更新订单更新用户余额


@shared_task
def bdi():
    # 从redis list中获取10条信息
    # 调用百度api接口
    # 将结果存入redis
    id_list = []
    url_list = []
    user_list = []
    data_list = r.list_lrange("baidulist", 0, 1)
    if len(data_list) < 2:
        print("等待中")
        return {'msg': '等待中'}
    for i in data_list:
        data = json.loads(i.decode('utf-8'))
        user_id = data.get('user_id')
        url = data.get('url')
        response = bdapi.idcard(url)
        if response != False:
            res = json.loads(response)
            username = res.get('words_result').get('姓名').get('words')
            race = res.get('words_result').get('民族').get('words')
            sex = res.get('words_result').get('性别').get('words')
            if sex == "男":
                sex = 0
            else:
                sex = 1
            birthday = res.get('words_result').get('出生').get('words')
            identity = res.get('words_result').get('公民身份号码').get('words')
            user_dict = {
                'username': username,
                'race': race,
                'sex': sex,
                'birthday': f'{birthday[0:4]}-{birthday[4:6]}-{birthday[6:8]}',
                'id_card': identity,
                'user': user_id,
            }
            user_list.append(user_dict)

        else:
            id_list.append(f"bdi{user_id}")
        url_list.append(i)
    print(url_list)
    print(id_list)
    print(user_list)

    identity_serial = IdentitySerializer(data=user_list, many=True)
    if identity_serial.is_valid():
        identity_serial.save()
    else:
        return {'msg': 'fail'}

    pipe = r.r.pipeline()
    pipe.multi()
    for i in url_list:
        pipe.lrem('baidulist', 1, i)  # 第二个参数是删除的数量，1 表示删除第一个匹配的元素
    if len(id_list) > 0:
        pipe.delete(*id_list)
    pipe.execute()


    print("调用百度api接口")


@shared_task
def get_cpu():
    channel_layer = get_channel_layer()
    send_data = ssh.get_cpu_info()
    async_to_sync(channel_layer.group_send)(
        '1',  # 房间组名
        {
            'type': 'send_to_chrome',  # 消费者中处理的函数
            'data': send_data
        }
    )
@shared_task
def check_order(order_id):
    CheckOrder(order_id)


@shared_task
def check_fileupload():
    data_list = []
    list_data = r.zset_zrangebyscore('fileupload', 0, int(time.time() - 60*1))
    if len(list_data) > 0:
        for i in list_data:
            data_list.append(i.decode())
            file_path = "./media/upload/{}".format(i.decode())
            if os.path.exists(file_path):
                shutil.rmtree(file_path)
                print("删除成功")
        r.zset_zrem('fileupload', *data_list)


